"""
@author: xiangping
@contact: xiangpingbu@gmail.com
@time: 2020/1/10 4:37 下午
@file: shaojie_controller
@Desc:
"""
import datetime
from typing import List

from flask import Blueprint, request, current_app

from app.database import convert
from app.models.po.shaojie.shaojie_model_input_po import ShaoJieInputPO
from app.models.po.shaojie.shaojie_predict_po import ShaoJiePredictPO
from app.models.po.shaojie.shaojie_rule_po import ShaoJieRulePO
from app.controllers.response.response import SuccessResult
from app.services.business import shaojie_biz_service
from app.utils.sys_utils import GaoLuEncoder, get_time_round_and_adjust, string_to_num, string_to_bool

bp = Blueprint('shaojie', __name__, url_prefix="/api/v1/shaojie")
shaojie_bp = bp


@shaojie_bp.route('/bellow/location', methods=['GET'])
def shaojie_bellow_location():
    ret = shaojie_biz_service.get_bellow_location()
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@shaojie_bp.route('/bellow/status/evaluation', methods=['GET'])
def shaojie_bellow_status_evaluation():
    """
    烧结终点状态评价
    :return:
    """
    ret = shaojie_biz_service.get_bellow_status_evaluation()
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@shaojie_bp.route('/current/info', methods=['GET'])
def get_current_info():
    """
    当前终点位置展示
    :return:
    """
    continuous = string_to_bool(request.args.get('continuous'))
    latest_id = string_to_num(request.args.get('latestId'))
    ret = shaojie_biz_service.get_status_info(continuous, latest_id)
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@shaojie_bp.route('/predict/info', methods=['GET'])
def get_predict_info():
    """
    预测终点位置展示
    :return:
    """
    continuous = string_to_bool(request.args.get('continuous'))
    latest_id = string_to_num(request.args.get('latestId'))
    ret = shaojie_biz_service.get_status_info(continuous, latest_id, time_point='future_5m')
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@shaojie_bp.route('/all/info', methods=['GET'])
def get_all_predict_info():
    start = request.args.get('from')
    end = request.args.get('to')

    if end is None or start is None:
        end_time = datetime.datetime.now()
        # ad-hoc
        # end_time = datetime.datetime.strptime("2020-02-17 23:59:00", "%Y-%m-%d %H:%M:%S")
        start_time = end_time - datetime.timedelta(hours=1)
    else:
        end_time = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
        start_time = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
    hour_diff = (end_time - start_time).seconds / (60 * 60)
    ret = shaojie_biz_service.get_total_status_info(start_time=start_time, end_time=end_time, span=hour_diff)
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@shaojie_bp.route('/batch', methods=['GET'])
def shaojie_batch_update():
    shaojie_biz_service.model_predict()
    return SuccessResult(detail="successfully insert ", encoder=GaoLuEncoder)


@shaojie_bp.route('/get_current_data', methods=['GET'])
def shaojie_latest_data():
    data: ShaoJieInputPO = shaojie_biz_service.get_shaojie_latest_data()
    return SuccessResult(detail=data, encoder=GaoLuEncoder)


@shaojie_bp.route('/mainData/group')
def shaojie_data_group():
    start: str = request.args.get('start')
    end: str = request.args.get('end')
    tag: str = request.args.get('tag')
    group_level: str = request.args.get("groupLevel")

    start: datetime.datetime = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
    end: datetime.datetime = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    r: List[dict] = shaojie_biz_service.get_shaojie_group_data(start, end, 'min', tag, group_level)
    return SuccessResult(detail=r, encoder=GaoLuEncoder)


@shaojie_bp.route('/mainData/info', methods=['GET'])
def get_shaojie_main_data():
    start = request.args.get('start')
    end = request.args.get('end')
    if start is None or end is None:
        now = datetime.datetime.now()
        start_time = get_time_round_and_adjust(now, step=0, round_level='hour')
        end_time = get_time_round_and_adjust(start_time, step=24, round_level='hour')
    else:
        start_time = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
        end_time = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")

    his_ret = shaojie_biz_service.get_shaojie_history_between(start_time, end_time, left="close", right="open",
                                                              order_by=ShaoJiePredictPO.DateTime.asc())

    ret = {}
    main_params = current_app.config['MAIN_PARAMS']
    for param in main_params:
        ret[param] = []

    for po in his_ret:
        for param in main_params:
            ret[param].append(po.__getattribute__(param))
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@shaojie_bp.route('/rule/update', methods=['POST'])
def save_rule():
    """
    保存规则
    :return:
    """
    location_from = request.json.get('locationFrom')
    location_to = request.json.get('locationTo')

    temp_from = request.json.get('tempFrom')
    temp_to = request.json.get('tempTo')

    # 只要为空,就不做任何处理
    if location_from is None or location_to is None or temp_from is None or temp_to is None:
        return SuccessResult(detail="success", encoder=GaoLuEncoder)

    # 找到当前规则,进行更新
    rule: ShaoJieRulePO = convert.query(ShaoJieRulePO, is_deleted=0).first()

    # 结果一致,就不做处理
    if float(location_from) == rule.location_from and \
            float(location_to) == rule.location_to and \
            float(temp_from) == rule.temp_from and \
            float(temp_to) == rule.temp_to:
        return SuccessResult(detail="success", encoder=GaoLuEncoder)
    new_rule = ShaoJieRulePO()
    new_rule.location_from = location_from
    new_rule.location_to = location_to

    new_rule.temp_from = temp_from
    new_rule.temp_to = temp_to
    new_rule.gmt_create = datetime.datetime.now()
    new_rule.gmt_modified = datetime.datetime.now()
    new_rule.is_deleted = 0

    # 更新历史记录
    convert.update_table(ShaoJieRulePO, dict(is_deleted=1), is_deleted=0)
    # 插入新记录
    convert.add_one(new_rule)

    result = dict(locationFrom=location_from,
                  locationTo=location_to,
                  tempFrom=temp_from,
                  tempTo=temp_to)

    return SuccessResult(detail=result, encoder=GaoLuEncoder)


@shaojie_bp.route('/rule/get', methods=['GET'])
def get_rule():
    rule: ShaoJieRulePO = convert.query(ShaoJieRulePO, is_deleted=0).first()
    result = dict(locationFrom=rule.location_from,
                  locationTo=rule.location_to,
                  tempFrom=rule.temp_from,
                  tempTo=rule.temp_to)
    return SuccessResult(detail=result)
